package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"like-master/cache"
	"like-master/models"
	"like-master/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	phone := c.PostForm("phone")
	password := c.PostForm("password")
	if phone == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var user models.User
	redis_key := "login_" + phone
	errorData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errorData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	err := models.DB.Where("phone=?", phone).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户失败",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errorData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var novel []models.Novel
	redis_key := "list_page_" + strconv.Itoa(page)
	models.DB.Offset(offset).Limit(size).Debug().Find(&novel)
	jsonData, _ := json.Marshal(&novel)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	var total int64
	models.DB.Model(&novel).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表成功",
		"data":  novel,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var novel models.Novel
	redis_key := "detail_" + id
	models.DB.Where("id=?", id).Debug().Find(&novel)
	jsonData, _ := json.Marshal(&novel)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": novel,
	})
	return
}
